<template>
  <div class="list" ref="wrapper">
    <div>
      <div class="area">
      <div class="title border-topbottom">您的位置</div>
      <div class="button-list">
        <div class="button-wrapper">
          <div class="button">{{this.currentCity}}</div>
        </div>
      </div>
    </div>
    <div class="area">
      <div class="title border-topbottom">热门城市</div>
      <div class="button-list">
        <div
          class="button-wrapper"
          v-for="item of hotCities"
          :key="item.id"
          @click="handleClickCity(item.name)"
        >
          <div class="button">{{item.name}}</div>
        </div>
      </div>
    </div>
    <div class="area" v-for="(item,key) of cities" :key="key" :ref="key">
      <div class="title border-topbottom">{{key}}</div>
      <div class="item-list">
        <div
          class="item border-bottom"
          v-for="innerText of item"
          :key="innerText.id"
          @click="handleClickCity(innerText.name)"
        >{{innerText.name}}</div>
      </div>
    </div>
    </div>
  </div>
</template>
<script>
import Bscroll from 'better-scroll'
import { mapState, mapMutations } from 'vuex'
export default{
  name: 'CityList',
  props: {
    cities: Object,
    hotCities: Array,
    letter: String
  },
  computed: {
    // 有两种实现方式，方式一
    ...mapState({
      'currentCity': 'city'
    })
    // 方式二 ...mapState(['city']),上面调用this.city即可
  },
  methods: {
    handleClickCity (city) {
      console.log(city)
      // this.$store.commit('editCity', city),调用commit向Mutations中提交数据
      this.editCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['editCity'])
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.wrapper)
  },
  watch: {
    // 这里是监控父组件传过来的letter
    letter () {
      if (this.letter) {
        // this.$refs返回一个map,可以通过键来访问其对应的内容，这里获取不同首字母对应的区块,类型是一个长度为1的数组
        const element = this.$refs[this.letter][0]
        this.scroll.scrollToElement(element)
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    position absolute
    top 1.58rem
    left 0
    right 0
    bottom 0
    overflow hidden
    .area
      .title
        height .64rem
        line-height .64rem
        background  #E0E0E0
        padding-left .2rem
      .button-list
        padding .1rem .6rem .1rem .1rem
        overflow hidden
        .button-wrapper
          float left
          width 33.33%
          .button
            margin .1rem
            text-align center
            border .02rem solid #ccc
            padding .1rem 0
      .item-list
        padding-left .2rem
        .item
          height .74rem
          line-height .74rem
</style>
